package com.edu.gdkm.servlet;

import com.edu.gdkm.dao.dypDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/modifyServlet")
public class modifyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HashMap<String, String> temp = new HashMap<>();
        HashMap<String, String> modify = new HashMap<>();
        temp.put("table", req.getParameter("table"));
        temp.put("name", req.getParameter("name"));
        try {
            dypDao dao = new dypDao();
            PreparedStatement ps;
            switch (temp.get("table")) {
                case "customer" :
                    temp.put("cid", req.getParameter("id"));
                    modify.put("cname", dao.str(temp.get("name")));
                    modify.put("ctel", req.getParameter("tel"));
                    break;
                case "film" :
                    temp.put("filmid", req.getParameter("id"));
                    modify.put("fid", req.getParameter("classify"));
                    modify.put("filmtime",
                            dao.str(req.getParameter("time")));
                    modify.put("filmprice", req.getParameter("price"));
                    break;
                case "filmegener" :
                    temp.put("kid", req.getParameter("id"));
                    modify.put("kinfo", dao.str(req.getParameter("hall") + "厅" +
                            req.getParameter("row") + "排" +
                            req.getParameter("seat") + "座"));
                    modify.put("ktime", dao.str(req.getParameter("time")));
                    modify.put("filmid", temp.get("name"));
                    break;
                default:

            }

            for (Map.Entry<String, String> entry : modify.entrySet()){
                String set = String.join("=", entry.getKey(), entry.getValue());
                for (Map.Entry<String, String> entry1 : temp.entrySet())
                    if (entry1.getKey().contains("id")){
                        String where = String.join("=", entry1.getKey(), entry1.getValue());
                        dao.update(temp.get("table"), set, where);
                    }
            }
            dao.close();
            resp.sendRedirect(req.getContextPath() + "/adminServlet");
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
